package com.pet.cart.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.api.client.ItemClient;
import com.pet.api.dto.ItemDTO;
import com.pet.cart.domain.po.Favor;
import com.pet.cart.domain.vo.FavorVO;
import com.pet.cart.mapper.FavorMapper;
import com.pet.cart.service.IFavorService;
import com.pet.common.domain.Result;
import com.pet.common.domain.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品收藏表 服务实现类
 * </p>
 *
 * @author Cookies
 * @since 2024-07-11
 */
@Service
@RequiredArgsConstructor
public class FavorServiceImpl extends ServiceImpl<FavorMapper, Favor> implements IFavorService {
    private final ItemClient itemClient;

    @Override
    public Result addItems2Favor(Integer itemId) {
        Integer userId = UserContext.getUser();
        Integer count = lambdaQuery()
                .eq(Favor::getUserId, userId)
                .eq(Favor::getItemId, itemId)
                .count();
        if (count > 0) {
            return Result.error("商品已经收藏过啦!");
        }
        Favor favor = new Favor();
        favor.setUserId(userId);
        favor.setItemId(itemId);
        boolean isSucceed = save(favor);
        return isSucceed ? Result.success() : Result.error();
    }

    @Override
    public List<FavorVO> getFavorListByUser() {
        Integer userId = UserContext.getUser();
        List<Favor> favorList = lambdaQuery()
                .eq(Favor::getUserId, userId)
                .list();
        if (CollUtil.isEmpty(favorList)) {
            return Collections.emptyList();
        }
        List<FavorVO> favorVOList = BeanUtil.copyToList(favorList, FavorVO.class);
        // 处理VO中的商品信息
        handleFavorItems(favorVOList);
        return favorVOList;
    }

    private void handleFavorItems(List<FavorVO> favorVOList) {
        // 获取商品id
        Set<Integer> itemIds = favorVOList.stream().map(FavorVO::getItemId).collect(Collectors.toSet());
        List<ItemDTO> items = itemClient.getItemsByIds(itemIds);
        if (CollUtil.isEmpty(items)) {
            return;
        }
        // 转为id到item的map
        Map<Integer, ItemDTO> itemMap = items.stream().collect(Collectors.toMap(ItemDTO::getId, Function.identity()));
        // 写入vo
        for (FavorVO favorVO : favorVOList) {
            ItemDTO item = itemMap.get(favorVO.getItemId());
            if (item == null) {
                continue;
            }
            favorVO.setName(item.getTitle());
            favorVO.setImage(item.getImage());
            favorVO.setPrice(item.getPrice());
        }
    }
}
